package com.desire.test;

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;

/**
 * @author desire
 */
public class _44_ReadWriteLock读写锁 {
    public static void main(String[] args) {

        // 官方的读写锁
        ReadWriteLock rwl = new ReadWriteLock() {
            @Override
            public Lock readLock() {
                return null;
            }

            @Override
            public Lock writeLock() {
                return null;
            }
        };


        ///////////////////////////////////////////////////////

        ReadWriteLockDemo rw = new ReadWriteLockDemo();
        // 一个线程进行写
        Thread w = new Thread(new Runnable() {
            @Override
            public void run() {
                rw.write((int) (Math.random() * 100));
            }
        }, "Write:");
        w.setPriority(10);
        w.start();

        // 100个线程进行读操作
        for (int i = 0; i < 50; i++) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    rw.read();
                }
            }, "Read:").start();
        }
    }

    /**
     * 自定读写锁
     */
    static class ReadWriteLockDemo {
        private final ReadWriteLock lock = new ReentrantReadWriteLock();
        private int number = 0;

        // 读
        public void read() {
            lock.readLock().lock(); // 上锁
            try {
                System.out.println(Thread.currentThread().getName() + ":" + number);
            } finally {
                lock.readLock().unlock(); // 释放锁
            }
        }

        // 写
        public void write(int number) {
            lock.writeLock().lock();// 上锁
            try {
                this.number = number;
                System.out.println(Thread.currentThread().getName() + ":" + number);
            } finally {
                lock.writeLock().unlock(); // 释放锁
            }
        }
    }
}
